import re
from datetime import timedelta

import cv2


def parse_srt(srt_path):
    def time_str_to_ms(t):
        h, m, s_ms = t.split(":")
        s, ms = s_ms.split(",")
        return int(h)*3600000 + int(m)*60000 + int(s)*1000 + int(ms)

    srt_entries = []
    with open(srt_path, 'r', encoding='utf-8') as f:
        blocks = f.read().split('\n\n')
        for block in blocks:
            lines = block.strip().splitlines()
            if len(lines) >= 3:
                times = lines[1].split(' --> ')
                start_ms = time_str_to_ms(times[0])
                end_ms = time_str_to_ms(times[1])
                content = "\n".join(lines[2:])
                match = re.search(r'dzoom_ratio: (\d+),.*altitude: ([\d.]+)', content)
                if match:
                    dzoom = match.group(1)
                    alt = match.group(2)
                    srt_entries.append({
                        'start': start_ms,
                        'end': end_ms,
                        'dzoom_ratio': dzoom,
                        'altitude': alt
                    })
    return srt_entries

from PIL import Image, ImageDraw, ImageFont
import numpy as np

# 加载中文字体（你可以换成自己系统的字体路径）
# font_path = "/usr/share/fonts/truetype/arphic/ukai.ttc"  # Linux 示例
font_path = "C:/Windows/Fonts/simhei.ttf"  # Windows 示例
font = ImageFont.truetype(font_path, 36)

def draw_chinese_text(img, text, pos, color=(255, 255, 255)):
    # 把OpenCV图像转为PIL图像
    img_pil = Image.fromarray(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))
    draw = ImageDraw.Draw(img_pil)
    draw.text(pos, text, font=font, fill=color)
    # 转回OpenCV图像
    return cv2.cvtColor(np.array(img_pil), cv2.COLOR_RGB2BGR)

